package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class OrderTccActionImpl implements OrderTccAction {
    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepareCreateOrder(BusinessActionContext ctx, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        //status为 0，表示订单是冻结状态
        Order order = new Order(orderId, userId, productId, count, money, 0);
        orderMapper.create(order);

        //第一阶段成功时，保存成功标记
        ResultHolder.setResult(OrderTccAction.class,
                                ctx.getXid(),//事务id
                                "p");//标记值随便写，后面只是判断存不存在
       return true;
    }

    //事务成功确认提交数据的操作
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //控制幂等性：多次提交时，不重复执行提交操作
        if(ResultHolder.getResult(OrderTccAction.class,ctx.getXid()) == null){
            return true;
        }
        /**
         * 上下文对象 BusinessActionContext 从第一阶段向第二阶段传递数据时，是转成json传递的
         */
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());
        orderMapper.updateStatus(orderId, 1);

        //提交成功后，删除标识
        ResultHolder.removeResult(OrderTccAction.class,ctx.getXid());

        return true;
    }

    //失败后，事务回滚的操作
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        //控制幂等性：多次提交时，不重复执行提交操作
        if(ResultHolder.getResult(OrderTccAction.class,ctx.getXid()) == null){
            return true;
        }
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);

        //回滚成功后，删除标识
        ResultHolder.removeResult(OrderTccAction.class,ctx.getXid());

        return true;
    }
}
